package blog.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.org.apache.bcel.internal.generic.IFNONNULL;

import blog.entities.User;
import blog.service.UserService;
import blog.service.impl.UserServiceImpl;

/**
 * Servlet implementation class Register
 */
@WebServlet("/mgrCenter")
public class ModifyUserController extends HttpServlet {
	private UserService userService = new UserServiceImpl();
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModifyUserController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// response.getWriter().append("Served at: ").append(request.getContextPath());
		
		// 解决浏览器到服务器端中文编码不一致问题
		req.setCharacterEncoding("UTF-8");
		// 解决服务器端到浏览器中文编码不一致问题
		resp.setContentType("text/html;charset=utf-8");
		
		System.out.println("欢迎来到modifyUserController");
		String option = req.getParameter("option");
		System.out.println("option=" + option);
		// 域对象.getParamter后一定要判断IFNOTNULL
		if (option != null) {
			switch (option) {
			case "deleteUser":
				deteleRow(req,resp);
				break;
			case "mgrCenter":
				goMgrCenter(req,resp);
				break;
			case "delMultiUser":
				deleteMutipleRow(req,resp);
				break;
			case "addUser":
				addRow(req,resp);
				break;
			case "showUser":
				showRow(req,resp);
				break;
			case "modifyUser":
				modifyRow(req,resp);
				break;
			default:
				break;
			}
		}
		
	}

	private void modifyRow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎进入modifyRow()");
		HttpSession session = req.getSession();
		PrintWriter writer = resp.getWriter();
		
		String id = req.getParameter("id");
		System.out.println("id:" + id);
		String wait = req.getParameter("wait");
		if (wait != null && wait.equals("1")) {
			System.out.println("进入了修改页面");
			if (session != null) {
				List<User> userList = userService.getSpecifiedUserList("id",id);
				if (userList != null) {
					session.setAttribute("modifyUserList", userList);
				}
				req.getRequestDispatcher("/WEB-INF/modify.jsp").forward(req, resp);
			}
		} else if (wait != null && wait.equals("0")) {
			if (id != null) {
				System.out.println("开始执行修改操作...");
				// 准备阶段须知
				// 由于表单有些(key,value)的value可为null,因此要寻找到value不为null的key
				// 由于option和wait也是key,不是修改用户信息用到的key,也要去除.
				
				// 为修改用户操作做准备
				Map<String, String[]> parameterMap = req.getParameterMap();
				Set<String> keySet = parameterMap.keySet();
				System.out.println("获取key集合(过滤不需要的key):");
				String keyStr = "";
				for (String s : keySet) {
					// 过滤名为option和wait的key
					if (s != null && !s.equals("option") && !s.equals("wait")) {
						// 过滤value为null的key
						String value = req.getParameter(s);
						if (value != null && !value.equals("")) {
							keyStr += s + ",";
						}
					}
				}
				
				System.out.println("keyStr: " + keyStr);
				System.out.println("过滤结束");
				
				// 增加成员操作准备阶段 - 拆分成员参数
				String[] user_key_params = keyStr.split(",");
				for (String s : user_key_params) {
					System.out.println(s);
				}
				
				// 增加成员操作准备阶段 - 合并成员参数到一个String[]
				String[] user_params = new String[user_key_params.length * 2];
				for (int i = 0; i < user_key_params.length; i++) {
					user_params[2 * i] = user_key_params[i];
					user_params[2 * i + 1] = req.getParameter(user_key_params[i]);
				}
				System.out.println("------------");
				for (String s : user_params) {
					System.out.println(s);
				}
				System.out.println();
				
				// 开始修改用户
				userService.userUpdate(Integer.parseInt(id), (Object[])user_params);
				
				if (session != null) {
					List<User> userList = userService.getAllUser();
					session.setAttribute("remainingUser", userList);
					req.getRequestDispatcher("/WEB-INF/mgrCenter.jsp").forward(req, resp);
				}
			}
		}
		
		if (writer != null) {
			writer.close();
		}
	}

	private void showRow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎进入showRow()");
		HttpSession session = req.getSession();
		PrintWriter writer = resp.getWriter();
		
		// 获取单个Id的用户
		String id = req.getParameter("id");
		
		List<User> userList = null;
		if (id != null) {
			userList = userService.getSpecifiedUserList("id",id);
			for (User user : userList) {
				System.out.println(user);
			}
			
			if (session != null) {
				session.setAttribute("showUserList",userList);
				req.getRequestDispatcher("/WEB-INF/show.jsp").forward(req, resp);
			}
		}

		if (writer != null) {
			writer.close();
		}
	}

	private void addRow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎进入addRow()");
		HttpSession session = req.getSession();
		PrintWriter writer = resp.getWriter();
		String wait = req.getParameter("wait");
		if(wait != null && wait.equals("1")) {
			// 重定向
			req.getRequestDispatcher("/WEB-INF/add.jsp").forward(req,resp);
		} else if (wait != null && wait.equals("0")) {
//			req.removeAttribute("wait");
//			System.out.println("调用了removeAttribute后在获取wait: " + (req.getParameter("wait")!=null));
			// 获取添加成员所需的参数
			Map<String, String[]> parameterMap = req.getParameterMap();
			Set<String> keySet = parameterMap.keySet();
			System.out.println("获取key集合(过滤option):");
			String keyStr = "";
			for (String s : keySet) {
				if (s != null && !s.equals("option") && !s.equals("wait")) {
					keyStr += s + ",";
				}
			}
			
			System.out.println("keyStr: " + keyStr);
			System.out.println();
			Set<Entry<String,String[]>> entrySet = parameterMap.entrySet();
			System.out.println("获取entrySet集合:");
			for (Entry<String, String[]> entry : entrySet) {
				System.out.print(entry.getKey() + "=");
				for (String value : entry.getValue()) {
					System.out.print(value + " ");
				}
			}
			
			
			// 增加成员操作准备阶段 - 拆分成员参数
			String[] user_key_params = keyStr.split(",");
			for (String s : user_key_params) {
				System.out.println(s);
			}
			
			// 增加成员操作准备阶段 - 合并成员参数到一个String[]
			String[] user_params = new String[user_key_params.length * 2];
			for (int i = 0; i < user_key_params.length; i++) {
				user_params[2 * i] = user_key_params[i];
				user_params[2 * i + 1] = req.getParameter(user_key_params[i]);
			}
			System.out.println("------------");
			for (String s : user_params) {
				System.out.println(s);
			}
			System.out.println();
			
			// 增加成员操作
			userService.userRegister((Object[])user_params);
			
			if (session != null) {
				
				List<User> userList = userService.getAllUser();
				if(userList != null && userList.size() != 0) {
					// 设置attribute
					session.setAttribute("remainingUser", userList);
					// 重定向
					req.getRequestDispatcher("/WEB-INF/mgrCenter.jsp").forward(req,resp);
					
				} else {
					writer.write("<p>无法查询到用户数据</p>");
				}
			}
		}

		if (writer != null) {
			writer.close();
		}
	}

	private void deleteMutipleRow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎进入deleteMutipleRow()");
		HttpSession session = req.getSession();
		PrintWriter writer = resp.getWriter();
		String ids = req.getParameter("id");
		if (ids != null && !ids.equals("")) {
			System.out.println(ids);
			String[] split = ids.split("-");
			for (String s : split) {
				System.out.println(s);
				int deletedRow = userService.userDelete("id",s);
				System.out.println("删除id=" + s + "是否成功(1:成功;0:失败): " + deletedRow);
			}
			

			if (session != null) {
				
				List<User> userList = userService.getAllUser();
				if(userList != null && userList.size() != 0) {
					// 设置attribute
					session.setAttribute("remainingUser", userList);
					// 重定向
					req.getRequestDispatcher("/WEB-INF/deleted.jsp").forward(req,resp);
					
				} else {
					writer.write("<p>无法查询到用户数据</p>");
				}
			}
		}
		if (writer != null) {
			writer.close();
		}
	}

	private void goMgrCenter(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎进入goMgrCenter()");
		HttpSession session = req.getSession();
		PrintWriter writer = resp.getWriter();
		if (session != null) {
			List<User> userList = userService.getAllUser();
			if (userList != null && userList.size() != 0) {
				// 设置attribute
				session.setAttribute("remainingUser", userList);
				// 重定向为什么要用req.而不用reps.getRequestDispatcher
				req.getRequestDispatcher("/WEB-INF/mgrCenter.jsp").forward(req,resp);
			} else {
				writer.write("<font size='2' color='red'>进入成员管理中心失败</font>");
			}
		}
		if (writer != null) {
			writer.close();
		}
	}

	private void deteleRow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("欢迎进入deteleRow()");
		String id = req.getParameter("id");
		System.out.println(id);
		// 从success.jsp获取到了要删除的用户id,那么接下来要做的就是删除数据库用户
		int deletedRow = userService.userDelete("id",id);
		
		// request的attribute已不可在于浏览器端使用,继而使用生命周期还存在的session域对象
		HttpSession session = req.getSession();
		PrintWriter writer = resp.getWriter();
		if (session != null) {
			// 无法删除或者早已删除了
			if (deletedRow == 0) {
				writer.write("<p>无法删除,可能是因为早已删除了</p>");
				System.out.println(deletedRow);
			} // 已成功删除
			else if (deletedRow > 0) {
				writer.write("<p>成功删除" + "共删除" + deletedRow + "条记录"  + "</p>");
				List<User> userList = userService.getAllUser();
				if(userList != null && userList.size() != 0) {
					// 设置attribute
					session.setAttribute("remainingUser", userList);
					// 重定向
					req.getRequestDispatcher("/WEB-INF/deleted.jsp").forward(req,resp);
					
				} else {
					writer.write("<p>无法查询到用户数据</p>");
				}
			} // 未知错误
			else {
				writer.write("<p>删除操作无成功执行,系统出错了</p>");
			}
		}
		if (writer != null) {
			writer.close();			
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
